#include "Avalon/CodecsTests/ReverseEncoder.hpp"
#include "Avalon/IO/Buffer.hpp"

using namespace Avalon;
using namespace Avalon::Codecs;
using namespace Avalon::Codecs::Tests;
using namespace Avalon::IO;
using namespace std;

ReverseEncoder::ReverseEncoder() {}

ReverseEncoder::~ReverseEncoder() {}

bool ReverseEncoder::IsEncodeInPlaceSupported() {
  return true;
}

void ReverseEncoder::Encode(const void* source, int sourceSize,
    void* destination, int destinationSize, int* encodedSize) {
  int length = min(sourceSize, destinationSize);
  const char* sourceIterator = static_cast<const char*>(source) + length - 1;
  char* destinationIterator = static_cast<char*>(destination);
  while(sourceIterator >= source) {
    *destinationIterator = *sourceIterator;
    ++destinationIterator;
    if(sourceIterator > source) {
      --sourceIterator;
    }
  }
  if(encodedSize != NULL) {
    *encodedSize = length;
  }
}

void ReverseEncoder::Encode(const void* source, int sourceSize,
    Buffer* destination, int* encodedSize) {
  int startingPoint = destination->GetSize();
  destination->Grow(sourceSize);
  Encode(source, sourceSize, destination->GetMutableData() + startingPoint,
    sourceSize, encodedSize);
}
